<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015-5-20
 * Time: 10:01
 */

namespace doumiaoduo\ueditor;


use yii\base\InvalidConfigException;
use yii\helpers\Url;
use yii\widgets\InputWidget;
use yii\helpers\Html;
use yii\helpers\Json;

class FileUpload extends InputWidget{

    public $clientOptions = [];

    public $serverParam = [];

    public $buttonOptions = [];
    public $view;
    public $asset;

    public function init()
    {
        parent::init();
        $id = str_replace('-', '_', $this->options['id']);
        if (isset($this->clientOptions['serverUrl'])) {
            $this->clientOptions['serverUrl'] = str_replace('action', 'uploadfile', $this->clientOptions['serverUrl']);
            $this->clientOptions['serverUrl'] = str_replace(urlencode('action'), 'uploadfile', $this->clientOptions['serverUrl']);
        }
        $this->clientOptions['csrf-param'] = \Yii::$app->request->csrfParam;
        $this->clientOptions['csrf-token'] = \Yii::$app->request->getCsrfToken();
        $this->clientOptions['isShow'] = false;
        $this->buttonOptions['id'] = isset($this->buttonOptions['id']) ? $this->buttonOptions['id'] : "image_upload_button_{$this->options['id']}";
        $this->view = $this->getView();
        $this->asset = FileUploadAsset::register($this->view);
    }

    public function run()
    {
        $strHtml = '';
        if ($this->hasModel()) {
            $strHtml .= Html::activeFileInput($this->model, $this->attribute, $this->options);
        } else {
            $strHtml .= Html::fileInput($this->name, $this->value, $this->options);
        }
        echo $strHtml;
        $this->registerClientScript();
    }

    public function registerClientScript()
    {
        $jss = "";
        $jss .= <<<JS
        var serverurl = '{$this->clientOptions['serverUrl']}';
JS;
        $this->view->registerJs($jss);
    }


}